<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['history:history:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['history:history:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['history:history:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['history:history:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="historyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="内容" align="center" prop="content" >
        <template slot-scope="scope">
          <div class="content-cell">{{ $formatContent(scope.row.content) }}</div>
        </template>
      </el-table-column>>
      <!-- <el-table-column label="图片" align="center" prop="img" /> -->
      <el-table-column label="图片" align="center" prop="img" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.img" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['history:history:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['history:history:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改历史对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <!-- <el-form-item label="图片" prop="img">
          <el-input v-model="form.img" placeholder="请输入图片" />
        </el-form-item> -->
        <el-form-item label="图片" prop="img">
          <el-upload
            ref="upload"
            :file-list="imgList"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            :auto-upload="false"
            :on-remove="handleRemove"
            :limit="1"
            list-type="picture-card"
            accept="image/*"
            action="#"
            :http-request="handleHttpRequest"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">请上传图片，大小不超过10MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHistory, getHistory, delHistory, addHistory, updateHistory } from "@/api/history/history";
import { uploadFile } from "@/api/history/history";
import imageCompression from "browser-image-compression";

export default {
  name: "History",
  data() {
    return {
      imgList: [],
      uploadFile: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 历史表格数据
      historyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        content: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {

    // 使用 Canvas 进行图片压缩，可以更精确地控制文件大小
    async compressImage(file) {
      const minSizeBytes = 450 * 1024; // 450KB 下限
      const maxSizeBytes = 1024 * 1024; // 1MB 上限

      // 所有图片都使用 Canvas 进行精确压缩，确保不会低于下限
      return await this.canvasCompress(file, minSizeBytes, maxSizeBytes);
    },

    // 使用 Canvas 进行精确压缩
    async canvasCompress(file, minSizeBytes, maxSizeBytes) {
      return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = new Image();

        img.onload = async () => {
          // 初始宽高
          let width = img.width;
          let height = img.height;

          // 计算缩放比例
          const ratio = width / height;

          // 如果图片很大，先进行初步缩放
          if (width > 2048 || height > 2048) {
            if (width > height) {
              width = 2048;
              height = 2048 / ratio;
            } else {
              height = 2048;
              width = 2048 * ratio;
            }
          }

          // 设置 canvas 尺寸
          canvas.width = width;
          canvas.height = height;

          // 绘制图片到 canvas
          ctx.drawImage(img, 0, 0, width, height);

          // 二分法查找合适的质量参数
          let quality = 0.8;
          let minQuality = 0.1;
          let maxQuality = 1.0;
          let attempts = 0;
          const maxAttempts = 10;

          let compressedBlob;

          while (attempts < maxAttempts) {
            attempts++;

            // 导出为 Blob
            compressedBlob = await new Promise(resolve => {
              canvas.toBlob(resolve, 'image/jpeg', quality);
            });

            console.log(`第 ${attempts} 次压缩尝试，质量: ${quality}, 大小: ${compressedBlob.size} bytes`);

            // 检查大小是否符合要求
            if (compressedBlob.size >= minSizeBytes && compressedBlob.size <= maxSizeBytes) {
              console.log('压缩成功，大小符合要求');
              break;
            }

            // 调整质量参数
            if (compressedBlob.size > maxSizeBytes) {
              // 太大了，降低质量
              maxQuality = quality;
              quality = (minQuality + quality) / 2;
            } else {
              // 太小了，提高质量
              minQuality = quality;
              quality = (quality + maxQuality) / 2;
            }

            // 如果质量调整过小，可能无法达到最小大小要求
            if (quality < 0.01) {
              console.warn('质量参数过低，无法达到最小大小要求');
              break;
            }
          }

          // 如果最终结果还是太小，使用最小质量重新压缩
          if (compressedBlob.size < minSizeBytes) {
            console.warn(`压缩后文件过小 (${compressedBlob.size} bytes)，使用最小质量重新压缩`);
            compressedBlob = await new Promise(resolve => {
              canvas.toBlob(resolve, 'image/jpeg', 0.95);
            });
          }

          // 转换为 File 对象
          const compressedFile = new File([compressedBlob], file.name, {
            type: 'image/jpeg',
            lastModified: Date.now()
          });

          console.log(`最终压缩结果: ${compressedFile.size} bytes`);
          resolve(compressedFile);
        };

        img.onerror = () => {
          reject(new Error('图片加载失败'));
        };

        // 读取文件
        const reader = new FileReader();
        reader.onload = e => {
          img.src = e.target.result;
        };
        reader.onerror = () => {
          reject(new Error('文件读取失败'));
        };
        reader.readAsDataURL(file);
      });
    },

    // 修改后的上传方法
    async uploadFileToServer(file) {
      const formData = new FormData();
      formData.append('imgPath', file);

      try {
        console.log('调用封面上传API，ID:', this.form.id || 0);
        const response = await uploadFile(this.form.id || 0, formData);

        console.log('封面上传响应:', response);
        if (response.code === 200) {
          this.form.img = response.url;
          this.$message.success('封面图片上传成功');
          return response;
        } else {
          throw new Error(response.msg || '上传失败');
        }
      } catch (error) {
        console.error('上传失败:', error);
        this.$message.error('封面图片上传失败: ' + error.message);
        throw error;
      }
    },

    handleHttpRequest(options) {
      console.log('图片上传请求处理:', options);
      this.uploadFileToServer(options.file);
    },

      // 文件移除处理
    handleRemove() {
      console.log('封面文件移除处理');
      this.uploadFile = null;
      this.form.img = null;
      this.imgList = [];
    },

    // 文件变化处理
    handleFileChange(file, imgList) {
      console.log('封面文件变化处理:', file, imgList);
      if (imgList.length > 0) {
        this.uploadFile = imgList[0].raw;
        this.imgList = [imgList[imgList.length - 1]]; // 只保留最后一个文件
        console.log('更新 uploadFile:', this.uploadFile);
      } else {
        this.uploadFile = null;
        this.imgList = [];
        console.log('清空 uploadFile');
      }
    },

    // 文件上传前处理
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过10MB!');
        return false;
      }

      this.uploadFile = file;
      return false; // 阻止自动上传
    },
    /** 查询历史列表 */
    getList() {
      this.loading = true;
      listHistory(this.queryParams).then(response => {
        this.historyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        content: null,
        img: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.imgList=[];
      this.title = "添加历史";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getHistory(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改历史";

        // 初始化文件列表
        if (this.form.img) {
          this.imgList = [{
            name: '图片',
            url: this.form.img
          }];
        } else {
          this.imgList = [];
          this.uploadFile=null;
        }
      });
    },
    /** 提交按钮 */
    // submitForm() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       if (this.form.id != null) {
    //         updateHistory(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       } else {
    //         addHistory(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (!valid) return;
        try {
          // 检查是否有文件需要上传，如果有则显示加载提示
          const hasFilesToUpload = this.uploadFile && this.uploadFile instanceof File;
          let loadingInstance = null;

          if (hasFilesToUpload) {
            loadingInstance = this.$loading({
              lock: true,
              text: '上传中请等待...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
          }

          // 处理图片上传
          if (this.uploadFile) {
            console.log('处理图片上传');
            console.log('提交前压缩图片');
            this.uploadFile = await this.compressImage(this.uploadFile);
            await this.uploadFileToServer(this.uploadFile);
          } else {
            console.log('跳过上传 - 没有选择图片文件');
          }


          // 提交表单数据
          console.log('提交表单数据:', this.form);
          const apiMethod = this.form.id ? updateHistory : addHistory;
          await apiMethod(this.form);
          // 关闭加载提示
          if (loadingInstance) {
            loadingInstance.close();
          }
          this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
          this.open = false;
          this.getList();
        } catch (error) {
          console.error('操作失败:', error);
           // 发生错误时关闭加载提示
          if (this.$loading) {
            // 关闭所有加载实例
            const loadingInstances = document.querySelectorAll('.el-loading-mask');
            if (loadingInstances.length > 0) {
              this.$loading().close();
            }
          }
          this.$message.error(`操作失败: ${error.message}`);
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除历史编号为"' + ids + '"的数据项？').then(function() {
        return delHistory(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('history/history/export', {
        ...this.queryParams
      }, `history_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
